/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */

function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}


let t1 = new TreeNode(1, new TreeNode(2, new TreeNode(3, null), null), null,)

var inorderTraversal = function (root) {
  // 递归解法

  // 中序遍历：左->中->右
  let ans = []

  if (root) {
    // 遍历左子树
    if (root.left) {
      ans = inorderTraversal(root.left)
    }

    // 压入中间节点
    ans.push(root.val)

    // 遍历右子树
    if (root.right) {
      ans = ans.concat(inorderTraversal(root.right))
    }
  }

  return ans
};

// Morris神级遍历
inorderTraversal = function (root) {
  let ans = []
  let cur = root

  while (cur) {
    if (cur.left) {
      let mr = cur.left
      while (mr.right != null && mr.right != cur) {
        // 找到左子树最右节点
        mr = mr.right
      }

      if (mr.right == null) {
        mr.right = cur
        cur = cur.left
      } else if (mr.right == cur) {
        ans.push(cur.val)
        mr.right = null
        cur = cur.right
      }
    } else {
      ans.push(cur.val)
      cur = cur.right
    }
  }
  return ans
}


console.log(inorderTraversal(t1))